package com.cardbaobao.cardbabyclient.ui.activity;

import android.content.res.ColorStateList;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.design.widget.AppBarLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.ui.activity.web.EventWebViewActivity;
import com.cardbaobao.cardbabyclient.ui.adapter.RaidersAdapter;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.callback.RecycleItemClickedCallback;
import com.cardbaobao.cardbabyclient.controller.CommonJumpController;
import com.cardbaobao.cardbabyclient.model.Banner;
import com.cardbaobao.cardbabyclient.model.RaidersLabelList;
import com.cardbaobao.cardbabyclient.model.RaidersList;
import com.cardbaobao.cardbabyclient.model.result.BannerResult;
import com.cardbaobao.cardbabyclient.model.result.RaidersLabelListResult;
import com.cardbaobao.cardbabyclient.model.result.RaidersListResult;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.utils.DensityUtil;
import com.cardbaobao.cardbabyclient.utils.ImageLoaderUtil;
import com.cardbaobao.cardbabyclient.utils.JsonUtil;
import com.cardbaobao.cardbabyclient.utils.ScreenUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.URLUtil;
import com.cardbaobao.cardbabyclient.widget.TitleBar;
import com.cardbaobao.cardbabyclient.widget.divider.VerticalItemDecoration;
import com.cardbaobao.cardbabyclient.widget.refresh.FooterLoadMore;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.stx.xhb.xbanner.XBanner;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import rx.Observable;
import rx.Subscriber;

/**
 * Created by Jiangzx on 2017 2017/6/26 13:49.
 */
public class CreditCardRaidersFilterActivity extends BaseActivity {
    private static final int START_PAGE=0;//分页开始页码
    public static final String RAIDERS_TYPE="raidersType";
    @BindView(R.id.title_bar)
    TitleBar titleBar;

    @BindView(R.id.xb_banner)
    XBanner xBanner;

    @BindView(R.id.main_appbar)
    AppBarLayout appBarLayout;

    @BindView(R.id.rg_raiders_condition)
    RadioGroup rgRaidersCondition;
    private List<RadioButton> radioButtons;

    @BindView(R.id.srLayout)
    SmartRefreshLayout srLayout;
    @BindView(R.id.footerLoadMore)
    FooterLoadMore footerLoadMore;

    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;

    private RaidersAdapter adapter;

    private int pageNumber =START_PAGE;//页码从0开始
    private String raidersType=null;
    private RaidersListResult listResult;
    private List<RaidersList.Raiders> raiders;

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);

        mCurrentPageId= Self.Page.app_credit_card_raiders_more_page;

        initIntent();
        titleBar.setLeftViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        ViewGroup.LayoutParams layoutParams=xBanner.getLayoutParams();
        layoutParams.height= (int) (ScreenUtil.getScreenWidth()*28/75.0f);
        xBanner.setLayoutParams(layoutParams);
        xBanner.setmAutoPalyTime(Constant.BANNER_INTERVAL_TIME);
        //下拉刷新头部
        footerLoadMore.setStateNoMoreDataStr("信用生活，享有就有");

        raiders=new ArrayList<>();
        adapter=new RaidersAdapter(raiders);
        adapter.setRecycleItemClickedCallback(new RecycleItemClickedCallback() {
            @Override
            public void onRecycleItemClicked(int position) {
                RaidersList.Raiders r=raiders.get(position);
                mIntent.setClass(mContext, EventWebViewActivity.class);
                String webUrl=r.getUrl();
                String webTitle=r.getName();
                switch (raidersType) {
                    case Constant.JBQ01060401://办卡
                        SelfUtils.buriedClickData(Self.Action.app_click_more_raiders_card_item,
                                Self.Action.app_click_more_raiders_card_item_des,
                                mEnterPageTime,
                                mCurrentPageId,
                                mPrePageId);
                        mIntent.putExtra(EventWebViewActivity.WEB_TYPE_I,27);
                        break;
                    case Constant.JBQ01060402://提额
                        SelfUtils.buriedClickData(Self.Action.app_click_more_raiders_upper_quota_item,
                                Self.Action.app_click_more_raiders_upper_quota_item_des,
                                mEnterPageTime,
                                mCurrentPageId,
                                mPrePageId);
                        mIntent.putExtra(EventWebViewActivity.WEB_TYPE_I,28);
                        break;
                    case Constant.JBQ01060403://羊毛
                        SelfUtils.buriedClickData(Self.Action.app_click_more_raiders_wool_item,
                                Self.Action.app_click_more_raiders_wool_item_des,
                                mEnterPageTime,
                                mCurrentPageId,
                                mPrePageId);
                        mIntent.putExtra(EventWebViewActivity.WEB_TYPE_I,29);
                        break;
                    case Constant.JBQ01060404://专题
                        SelfUtils.buriedClickData(Self.Action.app_click_more_raiders_topic_item,
                                Self.Action.app_click_more_raiders_topic_item_des,
                                mEnterPageTime,
                                mCurrentPageId,
                                mPrePageId);
                        mIntent.putExtra(EventWebViewActivity.WEB_TYPE_I,30);
                        break;
                }
                if(!TextUtils.isEmpty(webUrl)){
                    if(adapter.getRaidersType()==RaidersAdapter.TYPE_WOOL_RAIDERS){
                        //羊毛攻略
                        mIntent.putExtra(EventWebViewActivity.WEB_URL_S,
                                webUrl);
                    }else{
                        mIntent.putExtra(EventWebViewActivity.WEB_URL_S,
                                URLUtil.CBB_WEB_URL+webUrl);
                    }
                    mIntent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                    mIntent.putExtra(EventWebViewActivity.WEB_TITLE_S,
                            webTitle);
                    startActivity(mIntent);
                }
            }
        });

        rgRaidersCondition.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                for(RadioButton radioButton:radioButtons){
                    if(radioButton.isChecked()){
                        pageNumber=START_PAGE;
                        raidersType=radioButton.getTag().toString();
                        appBarLayout.setExpanded(true,true);
                        loadBannerData();
                        loadRecycleData(pageNumber,raidersType);
                        if(Constant.JBQ01060401.equals(raidersType)){
                            //办卡
                            SelfUtils.buriedClickData(Self.Action.app_click_more_raiders_card,
                                    Self.Action.app_click_more_raiders_card_des,
                                    mEnterPageTime,
                                    mCurrentPageId,
                                    mPrePageId);
                        }else if(Constant.JBQ01060402.equals(raidersType)){
                            //提额
                            SelfUtils.buriedClickData(Self.Action.app_click_more_raiders_upper_quota,
                                    Self.Action.app_click_more_raiders_upper_quota_des,
                                    mEnterPageTime,
                                    mCurrentPageId,
                                    mPrePageId);
                        }else if(Constant.JBQ01060403.equals(raidersType)){
                            //羊毛
                            SelfUtils.buriedClickData(Self.Action.app_click_more_raiders_wool,
                                    Self.Action.app_click_more_raiders_wool_des,
                                    mEnterPageTime,
                                    mCurrentPageId,
                                    mPrePageId);
                        }else if(Constant.JBQ01060404.equals(raidersType)){
                            //专题
                            SelfUtils.buriedClickData(Self.Action.app_click_more_raiders_topic,
                                    Self.Action.app_click_more_raiders_topic_des,
                                    mEnterPageTime,
                                    mCurrentPageId,
                                    mPrePageId);
                        }
                        break;
                    }
                }
            }
        });

        final LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        VerticalItemDecoration decoration=new VerticalItemDecoration(Constant.DIVIDER_COLOR,1);
        int padding= DensityUtil.dp2px(15.0f);
        decoration.setPaddingLeftRight(padding,padding);
        recyclerView.addItemDecoration(decoration);
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                srLayout.setEnableRefresh(verticalOffset==0);
            }
        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if(newState==RecyclerView.SCROLL_STATE_IDLE){
                    if(layoutManager.findFirstVisibleItemPosition()==0){
                        appBarLayout.setExpanded(true,true);
                    }
                }
            }
        });

        srLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                pageNumber++;
                loadRecycleData(pageNumber, raidersType);
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageNumber =START_PAGE;
                loadRecycleData(pageNumber,raidersType);
            }
        });

        raidersType=getIntent().getStringExtra(RAIDERS_TYPE);
        if(TextUtils.isEmpty(raidersType)){
            //默认办卡攻略类型为 羊毛
            raidersType=Constant.JBQ01060403;
        }
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        loadBannerData();
        loadTopLabel();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_credit_card_raiders_filter;
    }

    private void hideBanner(){
        appBarLayout.removeView(xBanner);
    }

    private void setSelectedRaidersType(){
        RadioButton rbt;
        for(int i=0;i<radioButtons.size();i++){
            rbt=radioButtons.get(i);
            if(rbt.getTag().equals(raidersType)){
                rbt.setChecked(true);
                break;
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(xBanner.getParent()!=null){
            xBanner.startAutoPlay();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(xBanner.getParent()!=null){
            xBanner.stopAutoPlay();
        }
    }

    private void loadBannerData(){
        showProgressDialog(false);
        Observable<String> observable=null;
        switch (raidersType){
            case Constant.JBQ01060401:
                //办卡
                observable= Api.getBannerData(Constant.GLB0323);
                break;
            case Constant.JBQ01060402:
                //提额
                observable=Api.getBannerData(Constant.GLB0324);
                break;
            case Constant.JBQ01060403:
                //羊毛
                observable=Api.getBannerData(Constant.GLB0325);
                break;
            case Constant.JBQ01060404:
                //专题
                observable=Api.getBannerData(Constant.GLB0326);
                break;
        }
        if(observable!=null){
            observable.subscribe(new Subscriber<String>() {
                @Override
                public void onCompleted() {
                    dismissProgressDialog();
                }

                @Override
                public void onError(Throwable e) {
                    dismissProgressDialog();
                    hideBanner();
                    ToastUtil.showToast(ApplicationHelper.
                            getApplicationContext().
                            getString(R.string.string_request_server_fail));
                }

                @Override
                public void onNext(String s) {
                    BannerResult bannerResult= JsonUtil.json2Object(s, BannerResult.class);
                    if(bannerResult.getCode()==Constant.SUC_CODE){
                        if(bannerResult.getData()!=null){
                            final List<Banner.CarouselFigureListBean> data=
                                    bannerResult.getData().getCarousel_figure_list();
                            if(data!=null&&data.size()>0){
                                xBanner.stopAutoPlay();
                                xBanner.setData(data,null);
                                xBanner.setmAdapter(new XBanner.XBannerAdapter() {
                                    @Override
                                    public void loadBanner(XBanner banner, Object model, View view, int position) {
                                        ImageLoaderUtil.displayImageWithPlaceHolder(URLUtil.CBB_IMG_URL+((Banner.CarouselFigureListBean)model).getImage(),
                                                (ImageView) view,
                                                R.mipmap.img_default_banner);
                                    }
                                });
                                xBanner.setOnItemClickListener(new XBanner.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(XBanner banner, int position) {
                                        CommonJumpController controller=new CommonJumpController(mContext);
                                        Banner.CarouselFigureListBean bean=data.get(position);
                                        Map<String,Object> extra=new HashMap<>();
                                        extra.put(CommonJumpController.FROM_PAGE,"办卡攻略-banner");
                                        switch (raidersType) {
                                            case Constant.JBQ01060401://办卡
                                                extra.put(EventWebViewActivity.WEB_TYPE_I,23);
                                                break;
                                            case Constant.JBQ01060402://提额
                                                extra.put(EventWebViewActivity.WEB_TYPE_I,24);
                                                break;
                                            case Constant.JBQ01060403://羊毛
                                                extra.put(EventWebViewActivity.WEB_TYPE_I,25);
                                                break;
                                            case Constant.JBQ01060404://专题
                                                extra.put(EventWebViewActivity.WEB_TYPE_I,26);
                                                break;
                                        }
                                        controller.bannerJump(bean,extra);
                                    }
                                });
                                if(xBanner.getParent()==null){
                                    appBarLayout.addView(xBanner);
                                }
                                xBanner.startAutoPlay();
                            }else{
                                hideBanner();
                            }
                        }else{
                            hideBanner();
                        }
                    }else{
                        hideBanner();
                        ToastUtil.showToast(bannerResult.getMsg());
                    }
                }
            });
        }
    }

    private void loadTopLabel(){
        Observable<String> observable=Api.getRaidersLabelList();
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
            }

            @Override
            public void onNext(String s) {
                RaidersLabelListResult listResult=JsonUtil.json2Object(s,RaidersLabelListResult.class);
                if(listResult!=null){
                    if(listResult.getCode()==Constant.SUC_CODE){
                        if(listResult.getData()!=null){
                            setLabelUi(listResult.getData());
                            loadRecycleData(pageNumber,raidersType);
                        }
                    }else{
                        ToastUtil.showToast(listResult.getMsg());
                    }
                }
            }
        });
    }

    /**设置顶部label数据*/
    private void setLabelUi(List<RaidersLabelList.RaidersLabel> data){
        RadioGroup.LayoutParams layoutParams=
                new RadioGroup.LayoutParams(0, RadioGroup.LayoutParams.MATCH_PARENT,1);
        ColorStateList color= ContextCompat.getColorStateList(mContext,R.color.selector_222_999);
        RaidersLabelList.RaidersLabel label;
        radioButtons=new ArrayList<>();
        Drawable colorDrawable=new ColorDrawable(0);
        for(int i=0;i<data.size();i++){
            label=data.get(i);
            RadioButton radioButton=new RadioButton(mContext);
            radioButton.setLayoutParams(layoutParams);
            radioButton.setTextColor(color);
            radioButton.setTextSize(TypedValue.COMPLEX_UNIT_SP,16.0f);
            radioButton.setText(label.getTitles());
            radioButton.setButtonDrawable(colorDrawable);
            radioButton.setBackgroundResource(R.color.transparent);
            radioButton.setGravity(Gravity.CENTER);
            radioButton.setTag(label.getCode());
            radioButtons.add(radioButton);
            rgRaidersCondition.addView(radioButton);
        }
        setSelectedRaidersType();
    }

    private void loadRecycleData(final int page, String code){
        showProgressDialog(false);
        Observable<String> observable=Api.getRaidersFilterData(page,code);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {
                dismissProgressDialog();
                if(recyclerView.getAdapter()==null){
                    recyclerView.setAdapter(adapter);
                }
                srLayout.finishRefresh();
                srLayout.finishLoadmore();
                if((pageNumber+1) <listResult.getTotal_page()){
                    //page是从0开始的，所以需要对page+1处理
                    footerLoadMore.showImage();
                    footerLoadMore.setStatePreLoading();
                    srLayout.setLoadmoreFinished(false);
                }else{
                    //没有更多数据了
                    footerLoadMore.hideImage();
                    footerLoadMore.setStateNoMoreData();
                    srLayout.setLoadmoreFinished(true);
                }
            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                handlePageWhenFailure();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
                if(recyclerView.getAdapter()==null){
                    recyclerView.setAdapter(adapter);
                }
            }

            @Override
            public void onNext(String s) {
                listResult=JsonUtil.json2Object(s,RaidersListResult.class);
                if(listResult!=null) {
                    if (listResult.getCode() == Constant.SUC_CODE) {
                        if (listResult.getData() != null) {
                            if (page == 0) {
                                raiders.clear();
                            }
                            raiders.addAll(listResult.getData());
                            switch (raidersType){
                                case Constant.JBQ01060403:
                                    //羊毛攻略
                                    adapter.setRaidersType(RaidersAdapter.TYPE_WOOL_RAIDERS);
                                    break;
                                case Constant.JBQ01060401:
                                    //办卡攻略
                                    adapter.setRaidersType(RaidersAdapter.TYPE_CREDIT_RAIDERS);
                                    break;
                                case Constant.JBQ01060402:
                                    //提额攻略
                                    adapter.setRaidersType(RaidersAdapter.TYPE_UPPER_QUOTA_RAIDERS);
                                    break;
                                case Constant.JBQ01060404:
                                    //专题攻略
                                    adapter.setRaidersType(RaidersAdapter.TYPE_TOPIC_RAIDERS);
                                    break;
                            }
                            adapter.notifyDataSetChanged();
                            if(page==0){
                                recyclerView.smoothScrollToPosition(0);
                            }
                        }
                    } else {
                        handlePageWhenFailure();
                        ToastUtil.showToast(listResult.getMsg());
                    }
                }
            }
        });
    }

    private void handlePageWhenFailure(){
        //加载出错时，处理分页
        pageNumber--;
        if(pageNumber<START_PAGE){
            pageNumber=START_PAGE;
        }
    }
}
